package cn.zmall.front.controller;

import cn.zmall.common.pojo.Result;
import cn.zmall.common.utils.ResultUtil;
import cn.zmall.manager.dto.front.Cart;
import cn.zmall.manager.dto.front.CartProduct;
import cn.zmall.sso.service.CartService;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Author BinBini
 * @Date 2020/11/26 10:19
 * @Version 1.0
 */
@RestController
@Api(value = "购物车")
public class CartController {

    @Reference
    private CartService cartService;

    @RequestMapping(value = "/member/addCart", method = RequestMethod.POST)
    @ApiOperation(value = "添加购物车")
    public Result<Object> addCart(@RequestBody Cart cart) {
        int result = cartService.addCart(cart.getUserId(), cart.getProductId(), cart.getProductNum());
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/cartList", method = RequestMethod.POST)
    @ApiOperation(value = "获取购物车内所有商品")
    public Result<List<CartProduct>> getCartList(Long userId) {
        List<CartProduct> cartProducts = cartService.getCartList(userId);
        return new ResultUtil<List<CartProduct>>().setData(cartProducts);
    }

    @RequestMapping(value = "/member/updateCartNum", method = RequestMethod.POST)
    @ApiOperation(value = "编辑购物车内商品的数量")
    public Result<Object> updateCartNum(@RequestBody Cart cart) {
        int result = cartService.updateCartNum(cart.getUserId(), cart.getProductId(), cart.getProductNum(), cart.getChecked());
        if(result == 0) {
            return new ResultUtil<Object>().setErrorMsg("编辑商品失败");
        }
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/checkAll", method = RequestMethod.POST)
    @ApiOperation(value = "是否全选")
    public Result<Object> editCheckAll(@RequestBody Cart cart) {
        int result = cartService.checkAll(cart.getUserId(), cart.getChecked());
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/delCartItem", method = RequestMethod.POST)
    @ApiOperation(value = "删除购物车内的商品")
    public Result<Object> delCartItem(@RequestBody Cart cart) {
        int result = cartService.delCartItem(cart.getUserId(), cart.getProductId());
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/delChecked", method = RequestMethod.POST)
    @ApiOperation(value = "删除勾选的商品")
    public Result<Object> delChecked(Long userId) {
        cartService.delChecked(userId);
        return new ResultUtil<Object>().setData(null);
    }
}
